<template>
  <div class="scaner" ref="scaner">
    <van-nav-bar
      title="扫一扫"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      style="background-color: #081c33;"
    />
    <div class="cover">
      <p class="line"></p>
      <span class="square top left"></span>
      <span class="square top right"></span>
      <span class="square bottom right"></span>
      <span class="square bottom left"></span>
      <p class="tips">将二维码放入框内，即可自动扫描</p>
    </div>
    <video
      class="source"
      ref="video"
      id="video"
      :width="videoWH.width"
      :height="videoWH.height"
       autoplay
       playsinline
       autofocus
      :controls="true"
    ></video>
   
  </div>
</template>
<script>
import jsQR from "jsqr";
import { userStore } from "../../stores/user.ts";
import { ElMessageBox, ElMessage } from "element-plus";
export default {
  name: "Scaner",
  props: {
    // 使用后置相机
    useBackCamera: {
      type: Boolean,
      default: true,
    },
    // 扫描识别后停止
    stopOnScaned: {
      type: Boolean,
      default: true,
    },
    drawOnfound: {
      type: Boolean,
      default: true,
    },
    // 线条颜色
    lineColor: {
      type: String,
      default: "red",
    },
    // 线条宽度
    lineWidth: {
      type: Number,
      default: 2,
    },
    // 视频宽度
    videoWidth: {
      type: Number,
      default: window.innerWidth,
    },
    // 视频高度
    videoHeight: {
      type: Number,
      default: window.innerHeight,
    },
    responsive: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showPlay: false,
      showBanner: true,
      opacity: 0,
      User_Code: null,
      Interface_Code: null,
      user: null,
      t1: null,
      t2: null,
      t3: null,
      t4: null,
      ts4: null,
    };
  },
  computed: {
    videoWH() {
      return { width: this.videoWidth, height: this.videoHeight };
    },
  },
  created() {
    this.user = userStore();
    this.User_Code = JSON.parse(sessionStorage.getItem("UserInfo")).sUser_Code;
    this.Interface_Code = sessionStorage.getItem("item");
  },
  methods: {
  
    startCamera() {
      try {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
          this.previousCode = null;
          this.parity = 0;
          const facingMode = this.useBackCamera
            ? { exact: "environment" }
            : "user";
          const handleSuccess = (stream) => {
            this.$refs.video.srcObject = stream;
            const playPromise = this.$refs.video.play();
            playPromise.then(() => {
              this.scanQRCode();
            });
            this.$refs.video.focus();
          };
          navigator.mediaDevices
            .getUserMedia({
              video: {
                 facingMode,
             width: { min: 640},
              height:{ min: 480},
              frameRate: 60,
              focusMode: "continuous",
              focusDistance: { exact: 10000 },
                
              },
            })
            .then(handleSuccess)
            .catch((error) => {
              this.$emit("error-captured", error);
            });
        }
      } catch (error) {
        console.error("无法访问摄像头", error);
      }
    },
   
    onClickLeft() {
      this.$router.push("/souye");
    },

    scanQRCode() {
      const video = this.$refs.video;
      // const canvas = this.$refs.canvas;
      const tick = () => {
        if (video.readyState === video.HAVE_ENOUGH_DATA) {
        const canvasElement = document.createElement('canvas');
        const canvas = canvasElement.getContext('2d');
        canvasElement.height = this.$refs.video.videoHeight;
        canvasElement.width = this.$refs.video.videoWidth;
        canvas.drawImage(this.$refs.video, 0, 0, canvasElement.width, canvasElement.height);
        const imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
        const code = jsQR(imageData.data, imageData.width, imageData.height, {
          inversionAttempts: 'dontInvert',
        });
        if (code) {
          var keyValue = code.data.split("&");
          console.log(keyValue);
          var obj = {};
          for (var i = 0; i < keyValue.length; i++) {
            //循环分割挂过后的地址
            var item = keyValue[i].split("=");
            var key = item[0];
            var value = item[1];
            obj[key] = value;
          }
          console.log(obj);
          sessionStorage;
          this.user.xqlist = obj;
          sessionStorage.setItem("xq", JSON.stringify(obj));
          axios
            .post(
              window.globalUrl.server + "Service.asmx/Get_CheckSub_Data",
              JSON.stringify({
                User_Code: this.User_Code,
                Interface_Code: this.Interface_Code,
                Check_No: obj.Check_No,
              })
            )
            .then((res) => {
              if (res.data.RltCode == 1) {
                this.user.Get_CheckSub_Data1 = JSON.parse(res.data.RltData);
                sessionStorage.setItem(
                  "data1",
                  JSON.stringify(JSON.parse(res.data.RltData))
                );
                axios
                  .post(
                    window.globalUrl.server + "Service.asmx/Get_ZytzEndInfo",
                    JSON.stringify({
                      User_Code: this.User_Code,
                      Interface_Code: this.Interface_Code,
                      Pson_CardID: this.user.Get_CheckSub_Data1.Pson_CardID,
                    })
                  )
                  .then((res) => {
                    if (res.data.RltCode == 1) {
                      this.user.Tz_End = JSON.parse(res.data.RltData);
                      sessionStorage.setItem(
                        "Tz_End",
                        JSON.stringify(JSON.parse(res.data.RltData))
                      );
                      // this.fullStop();
                      // this.$router.replace("/souye");
                    }else{
                      this.user.Tz_End={}
                       sessionStorage.setItem(
                        "Tz_End",
                        JSON.stringify(JSON.parse(res.data.RltData))
                      );
                    }
                  })
                  .catch((eorro) => {
                    console.log(eorro);
                  });
                  this.fullStop();
                  this.$router.replace("/souye");
              } else {
                if (res.data.RltCode == 0) {
                  ElMessage.error(res.data.RltMsg);
                }
                router.replace("/souye");
              }
            })
            .catch((eorro) => {
              // ElMessage.error("网络不稳定,请联系工作人员");
              // router.replace("/souye");
            });
        }
      }
      requestAnimationFrame(tick)
      }
      tick();
    },

    run() {
      requestAnimationFrame(this.scanQRCode);
    },
    found(code) {
      if (this.previousCode !== code) {
        this.previousCode = code;
        this.parity = 0; // 重置计数器
      } else {
        this.parity += 1;
        if (this.parity >= 2) {
          this.parity = 0;
          this.$emit("code-scanned", code);
        }
      }
    },
    // 完全停止
    fullStop() {
      if (this.$refs.video && this.$refs.video.srcObject) {
        // Quagga.stop();
        this.$refs.video.srcObject.getTracks().forEach((t) => t.stop());
      }
    },
  },
  mounted() {
    // this.canvas = this.$refs.canvas.getContext("2d");
    this.startCamera();

     this.$refs.video.focus();
  },
  beforeDestroy() {
    // Quagga.stop();
    this.fullStop();
  },
};
</script>

<style lang="css" scoped>
.scaner {
  position: fixed;
  width: 100%;
  height: 100%;
  height: -webkit-calc(100%);
  height: -moz-calc(100%);
  height: -ms-calc(100%);
  height: -o-calc(100%);
  height: calc(100%);
}
#canvas {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  /* transform: translate(-50%,-50%); */
}
#video {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
}
.scaner .banner {
  width: 100%;
  position: absolute;
  top: 16px;
  left: 50%;
  margin-left: -170px;
  background: #fa74a2;
  border-radius: 8px;
  box-sizing: border-box;
  padding: 12px;
  opacity: 0.9;
  box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.2);
}
.scaner .banner .text {
  padding: 0;
  margin: 0;
  color: #ffffff;
  font-size: 12px;
  text-align: justify;
  text-align-last: left;
}
.scaner .banner .close_icon {
  display: inline-block;
  height: 24px;
  width: 24px;
  background: url("../assets/close.png") no-repeat center;
  background-size: auto 100%;
  position: absolute;
  right: 8px;
  top: 8px;
}
.scaner .cover {
  height: 220px;
  width: 220px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border: 0.5px solid #999999;
  z-index: 1111;
}
.scaner .cover .line {
  width: 200px;
  height: 1px;
  margin-left: 10px;
  background: #5f68e8;
  background: linear-gradient(
    to right,
    transparent,
    #5f68e8,
    #0165ff,
    #5f68e8,
    transparent
  );
  position: absolute;
  -webkit-animation: scan 1.75s infinite linear;
  -moz-animation: scan 1.75s infinite linear;
  -ms-animation: scan 1.75s infinite linear;
  -o-animation: scan 1.75s infinite linear;
  animation: scan 1.75s infinite linear;
  -webkit-animation-fill-mode: both;
  -moz-animation-fill-mode: both;
  -ms-animation-fill-mode: both;
  -o-animation-fill-mode: both;
  animation-fill-mode: both;
  border-radius: 1px;
}
.scaner .cover .square {
  display: inline-block;
  height: 20px;
  width: 20px;
  position: absolute;
}
.scaner .cover .square.top {
  top: 0;
  border-top: 1px solid #5f68e8;
}
.scaner .cover .square.left {
  left: 0;
  border-left: 1px solid #5f68e8;
}
.scaner .cover .square.bottom {
  bottom: 0;
  border-bottom: 1px solid #5f68e8;
}
.scaner .cover .square.right {
  right: 0;
  border-right: 1px solid #5f68e8;
}
.scaner .cover .tips {
  position: absolute;
  bottom: -48px;
  width: 100%;
  font-size: 14px;
  color: #ffffff;
  opacity: 0.8;
}
@-webkit-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-moz-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-o-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
</style>
